/**
 * 
 */
package com.lane.sidecn.security.service;

import java.util.Iterator;
import java.util.List;

import org.acegisecurity.ConfigAttributeDefinition;
import org.acegisecurity.SecurityConfig;
import org.acegisecurity.intercept.web.FilterInvocationDefinitionSource;
import org.acegisecurity.intercept.web.PathBasedFilterInvocationDefinitionMap;

import com.lane.sidecn.security.model.Resource;
import com.lane.sidecn.security.model.Role;

/**
 * 从数据库中读取资源-角色记录，并添加到Acegi配置属性中。
 * @author 忽吉烈
 *
 */
public class FilterInvocationDefinitionSourceImpl extends
		PathBasedFilterInvocationDefinitionMap implements
		FilterInvocationDefinitionSource {

	private ResourceManager resourceManager;
	
	/**
	 * 
	 */
	public FilterInvocationDefinitionSourceImpl() {
		super();
		setConvertUrlToLowercaseBeforeComparison(true);
	}

	@Override
	public ConfigAttributeDefinition lookupAttributes(String url) {
		return super.lookupAttributes(url);
	}
	
	private void init()
	{
		//TODO 从数据库中读取Resource-Role数据
		ConfigAttributeDefinition config ;
		SecurityConfig sc;
		List<Resource> resourceList = resourceManager.getAll();
		for(Resource resource : resourceList)
		{
			Iterator<Role> it = resource.getRoles().iterator();
			while(it.hasNext())
			{
				Role role = it.next();
				config = new ConfigAttributeDefinition();
				sc = new SecurityConfig(role.getRoleName());
				config.addConfigAttribute(sc);
				addSecureUrl(resource.getUrl(), config);
			}
		}
	}

	public ResourceManager getResourceManger() {
		return resourceManager;
	}

	public void setResourceManger(ResourceManager resourceManager) {
		this.resourceManager = resourceManager;
		init();
	}

}
